package v1

import (
	"backend/middleware/cookie"
	"backend/middleware/wx"
	"backend/models"
	"backend/pkg/push"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
)

func Regist(c *gin.Context) {
	userStr := c.Query("user")

	wxStruct := models.WxUser{}
	json.Unmarshal([]byte(userStr), &wxStruct)
	var uid int
	uid = models.ExistUserByOpenid(wxStruct.Openid)
	if uid == 0 {
		uid = models.AddUser(wxStruct)
	}

	push.PushFeedBack(c, "测试内容", "很温馨的提醒", wxStruct.Openid)
	c.JSON(200, gin.H{
		"code": 0,
		"msg":  uid,
	})
}

/**
	微信登录
 */
func Login(c *gin.Context) {
	code := c.Query("code")

	fmt.Println(code)
	if code == "" || len(code) == 0 {
		c.JSON(200, gin.H{
			"code": 1,
			"msg":  "less code",
		})
		return
	}

	wx.Code = code
	if wx.CookieKey = c.DefaultQuery("cookieKey", ""); wx.CookieKey == "" {
		wx.CookieKey = cookie.GetCookieKey(code)
	}

	wxMap, ok := wx.GetSessionKey(c)
	if !ok {
		c.JSON(200, gin.H{
			"code": 1,
			"msg":  "服务出错，请查看日志",
		})
		return
	}
	c.JSON(200, gin.H{
		"code":      0,
		"msg":       wxMap["openid"].(string),
		"cookieKey": wx.CookieKey,
	})
	return
}
